package com.yry.ams.util;

import com.yry.ams.ex.BaseErrorException;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

/**
 * Created by Administrator on 2021/11/4.
 */
public class FileUtils {

    public static BufferedImage readImgBuffer(String imgPath){
        BufferedImage imgRead = null;
        File imgFile = new File(imgPath);
        try {
            if(imgFile.exists()){
                //从本地读取
                imgRead = ImageIO.read(imgFile);
            }else{
                //从网路读取
                URL imgUrl= new URL(imgPath);
                imgRead = ImageIO.read(imgUrl);
            }
        } catch (IOException e) {
            throw new BaseErrorException("加载图片I/O异常： "+e.getMessage());
        }
        return imgRead;
    }


    /**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     */
    public static String encodeBase64File(String path) throws Exception {
        File  file = new File(path);
        if(!file.exists()){
            return null;
        }
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
}
